from django.shortcuts import render, get_object_or_404
from .models import Bulletin
import mistune
from django.http import HttpResponse
import json

# Create your views here.

def index(request):
	all_bull = Bulletin.objects.all().order_by('-priority')
	context = {'all_bull': all_bull}
	# context = {"yes":"no"}
	return render(request, "home/index.html", context=context)

def bulletin(request, bull_num):
	bull = get_object_or_404(Bulletin, bull_id=bull_num)
	context = {'title': bull.title, 'date': bull.date}
	render_md = mistune.create_markdown(plugins=['strikethrough', 'table'])
	markdown_html = render_md(bull.body)
	context['body'] = markdown_html
	return render(request, 'home/bulletin.html', context=context)

def theme_settings(request): # api, 用于查询用户主题
	if request.user.username == '':
		return HttpResponse(json.dumps({'theme': 'default', 'user': 'no'}))
	return HttpResponse(json.dumps({'theme': request.user.userinfo.theme, 'user': 'yes'}))

def theme_write(request): # api, 用于修改用户主题
	if request.user.username == '':
		return HttpResponse(json.dumps({'ok': 'no user login'}))
	theme_new = request.POST['theme']
	now_login_user = request.user
	now_login_user.userinfo.theme = theme_new
	now_login_user.userinfo.save()
	now_login_user.save()
	return HttpResponse(json.dumps({'ok': now_login_user.userinfo.theme}))
